package com.wangjw.tuling.netty.rpc.util;

import com.wangjw.tuling.netty.rpc.common.RpcException;
import com.wangjw.tuling.netty.rpc.common.RpcRequest;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.springframework.objenesis.Objenesis;
import org.springframework.objenesis.ObjenesisStd;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by wangjianwen on 2018/12/11.
 */
public class ProtostuffSerializer implements Serializer {

    private static Objenesis objenesis = new ObjenesisStd(true);

    private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();

    @SuppressWarnings("unchecked")
    private static <T> Schema<T> getSchema(Class<T> cls) {
        Schema<T> schema = (Schema<T>) cachedSchema.get(cls);
        if (schema == null) {
            schema = RuntimeSchema.createFrom(cls);
            if (schema != null) {
                cachedSchema.put(cls, schema);
            }
        }
        return schema;
    }

    @Override
    public <T> Object deSerialize(byte[] bytes, Class<T> clazz) {
        try {
            T message = objenesis.newInstance(clazz);
            Schema<T> schema = getSchema(clazz);
            ProtostuffIOUtil.mergeFrom(bytes, message, schema);
            return message;
        } catch (Exception e) {
            throw new RpcException(e.getMessage(), e);
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> byte[] serialize(T obj) {
        Class<T> cls = (Class<T>) obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema<T> schema = getSchema(cls);
            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            throw new RpcException(e.getMessage(), e);
        } finally {
            buffer.clear();
        }
    }

    public static void main(String[] args) {
        RpcRequest request = new RpcRequest();
        request.setMethodName("add");
        request.setServiceName("CalculatorServiceImpl");
        request.setId("1");

        ProtostuffSerializer serializer = new ProtostuffSerializer();
        byte[] bytes = serializer.serialize(request);
        System.out.println(bytes.length);

        RpcRequest rpcRequest = (RpcRequest) serializer.deSerialize(bytes, RpcRequest.class);
        System.out.println(rpcRequest);
        System.out.println(rpcRequest.getMethodName());
        System.out.println(rpcRequest.getServiceName());
        System.out.println(rpcRequest.getId());
    }
}
